package com.kdtech.analyse.video;
import java.util.Date;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;

import com.kdtech.crawler.CrawlHTML;
import com.kdtech.entity.crawler.UrlMeta;
import com.kdtech.entity.data.NewsMeta;
import com.kdtech.utils.DateUtils;
import com.kdtech.utils.StringUtils;
import com.kdtech.analyse.AnalyseNews;
/**
 * http://www.tudou.com/ 土豆网
 * @author allen
 */
public class TudouAnalyse implements AnalyseNews {

	
	public boolean isDetailPage(String url) {
		boolean bRet = false;
		//http://www.tudou.com/programs/view/b3K2tiU7T_4
		String[] regex = {
				"http://www.tudou.com/programs/view/.*",
				"http://www.tudou.com/listplay/.*.html",
				"http://www.tudou.com/listplay/.*/.*.html",
				};
		for (int i = 0; i < regex.length; i++) {
			if (url.matches(regex[i])) {
				return true;
			}
		}
		return bRet;
	}

	
	public NewsMeta parserHtml(UrlMeta urlMeta) {
		NewsMeta video = new NewsMeta();
		if (urlMeta.getHtml() == null) {
		}
		String htmltxt = urlMeta.getHtml();
		String url = urlMeta.getUrl();
		video.setUrl(url);
		String title = null;
		String desc = null;
		Long date = null;
		String dateStr = null;

		Document doc = Jsoup.parse(htmltxt);
		if(doc.select("html body div.all div.content div.notice_panel").size()>0){
		}
			title =doc.select("body#p-pi.page_play > div.videowrap > div.vcate > ul.vci > li.last > span#vcate_title").text();
			if(title==null || title.trim().length()==0){
				title =doc.select("h1.videoKw").text();
				if(title==null || title.trim().length()==0){
					title = doc.select("title").text();
					if (title!=null){
						title = StringUtils.substringBefore(title, "_");
					}
					int pos = title.indexOf("_在线视频观看_");
					if(pos!=-1){
						title = title.substring(0,pos);
					}
				}
			}
			String tempdate=doc.select("p.v_user").html();
			if (StringUtils.isNotBlank(tempdate)){
				if(tempdate.indexOf("date=\"")!=-1){
					tempdate=tempdate.substring(tempdate.indexOf("date=\"")+"date=\"".length());
					if(tempdate.indexOf("\"")!=-1){
						tempdate=tempdate.substring(0,tempdate.indexOf("\""));
						try {
							date=Long.parseLong(tempdate);

						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}
			}
			if (date==null){
				if(htmltxt.indexOf(",pt:")!=-1){
					tempdate=htmltxt.substring(htmltxt.indexOf(",pt:")+",pt:".length());
					if(tempdate.indexOf("}")!=-1){
						tempdate=tempdate.substring(0,tempdate.indexOf("}"));
						tempdate=tempdate.replaceAll("\n", "");
						tempdate=tempdate.replaceAll("\r\n", "").trim();

						try {
							date=Long.parseLong(tempdate);

						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				}
			}
			if (date==null){
				String script = doc.select("script").html();
				script = StringUtils.substringAfter(script,",pt:");
				script = StringUtils.substringBefore(script, ",");
				if (script!=null){
					script = script.replace("\r", "");
					script = script.replace("\n", "");
				}
				tempdate = script;
				try {
					date=Long.parseLong(tempdate);
					if(date==0){
						UrlMeta responseToURL = CrawlHTML.responseToURL(url);
						doc = Jsoup.parse(responseToURL.getHtml());
						 script = doc.select("script").html();
						script = StringUtils.substringAfter(script,",pt:");
						script = StringUtils.substringBefore(script, ",");
						if (script!=null){
							script = script.replace("\r", "");
							script = script.replace("\n", "");
						}
						tempdate = script;
						try {
							date=Long.parseLong(tempdate);
						} catch (Exception e) {
							// TODO: handle exception
						}
					}
				} catch (Exception e) {
					// TODO: handle exception
				}
			}
			if(date==null){
				date = DateUtils.matchDate(doc.select("p.v_user").html());
				if(date==null){
					String substringBetween = StringUtils.substringBetween(htmltxt, ",pt:",",");
					if(substringBetween!=null){
						substringBetween=substringBetween.trim();
						try {
							date = new Date(Long.parseLong(substringBetween)).getTime();
						} catch (NumberFormatException e) {
						}
					}else{
						 substringBetween = StringUtils.substringBetween(htmltxt, ",index:","-");
						 date = DateUtils.matchDate(substringBetween);
					}
				}
			}
			if(StringUtils.isBlank(desc)){
				desc = doc.select(".v_desc").text();
			}

			video.setTitle(StringUtils.trimSpace(title));
			video.setContent(desc);
			video.setDate(date);
			/**
			 * 解析用于更新的地址
			 */
			String updateClick="NULL";
			String iCode = StringUtils.substringBetween(htmltxt, "icode: '","'");
			if(StringUtils.isBlank(iCode)){
				 iCode = StringUtils.substringBetween(htmltxt, "icode: \"","\"");

			}
			if(StringUtils.isNotBlank(iCode)){
			  updateClick="http://index.youku.com/dataapi/getData?jsoncallback=module_data_playnum_get&num=100011&icode="+iCode+"&_=1379907712339";
			}
			String updateComment="NULL";
			String iid = StringUtils.substringBetween(htmltxt, "iid:", ",").trim();
			if(StringUtils.isNotBlank(iid)){
				updateComment = "http://www.tudou.com/comments/itemnewcomment.srv?jsoncallback=module_data_comment_get&iid="+iid;
			}

			video.setUpdateUrl(updateClick+"###"+updateComment);
			NewsMeta update = Update(video);
			if(update!=null){
				video.setCommentNum(update.getCommentNum());
				video.setClickNum(update.getClickNum());
			 }

			String author=doc.select("p.v_user").text();
			if(StringUtils.isBlank(author)){
				author=StringUtils.substringBetween(htmltxt, ",onic:",",");
				if (author!=null){
					author=author.replace("\"", "").trim();
				}
			}
			video.setAuthor(author);
		    return video;
	}
	
	public NewsMeta Update(NewsMeta meta) {
		if(meta!=null){
			String updateUrl = meta.getUpdateUrl();
			if(updateUrl!=null){
				String[] split = updateUrl.split("###");
				if(split.length==2){
					String updateClick = split[0];
					if(!"NULL".equals(updateClick)){
						UrlMeta responseToURL = CrawlHTML.responseToURL(updateClick);
						if(responseToURL!=null){
							String html = responseToURL.getHtml();
							if(html!=null){
								String substringBetween = StringUtils.substringBetween(html, "\"totalVv\":","}");
								try {
									int parseInt = Integer.parseInt(substringBetween);
									meta.setClickNum(parseInt);
								} catch (NumberFormatException e) {
								}
							}
						}
					}
					String updateComment= split[1];
					if(!"NULL".equals(updateComment)){
						UrlMeta responseToURL = CrawlHTML.responseToURL(updateComment);
						if(responseToURL!=null){
							String html = responseToURL.getHtml();
							if(html!=null){
								String substringBetween = StringUtils.substringBetween(html, "\"total\":",",");
								try {
									int parseInt = Integer.parseInt(substringBetween);
									meta.setCommentNum(parseInt);
								} catch (NumberFormatException e) {
								}
							}
						}
					}

				}

			}
		}
		return null;
	}
	public static void main(String[] args) throws Exception {
		TudouAnalyse a = new TudouAnalyse();
		String url = "http://www.tudou.com/programs/view/4C22wC9Nc5E/";
		UrlMeta meta = CrawlHTML.responseToURL(url);
		NewsMeta parserHtml = a.parserHtml(meta);
		System.out.println(parserHtml);
//		String str="%7B%22videoid%22%3A%22120023337%22%2C%22userid%22%3A%2238249615%22%2C%22oldSid%22%3A-1%7D";
//		System.out.println(java.net.URLDecoder.decode(str, "utf-8"));
	}


	
}
